package component

import (
	"context"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/component/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/dao"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
)

type sComponent struct{}

var l = g.Log("logger for Component")

func New() *sComponent {
	return &sComponent{}
}

func init() {
	l.SetFlags(glog.F_FILE_LONG)
	service.RegisterComponent(New())
}

func (s *sComponent) List(ctx context.Context, in *v1.ListInput) (out *v1.ListOutput, err error) {
	md := dao.AppComponent.Ctx(ctx)
	cls := dao.AppComponent.Columns()
	if in.Type != 0 {
		md = md.Where(cls.Type, in.Type)
	}
	if in.Name != "" {
		md = md.Where(cls.Name, in.Name)
	}
	if in.AppCode != "" {
		md = md.Where(cls.AppCode, in.AppCode)
	}
	out = &v1.ListOutput{}
	if err = md.Limit((in.Page-1)*in.Size, in.Size).ScanAndCount(&out.Data, &out.Total, true); err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.ListComponentFailed, in))
	}
	return out, nil
}
func (s *sComponent) Info(ctx context.Context, in *v1.InfoInput) (out *v1.InfoOutput, err error) {
	return nil, nil
}

func (s *sComponent) Add(ctx context.Context, in *v1.AddInput) (out *v1.AddOutput, err error) {
	l.Info(ctx, "Add")

	id, err := dao.AppComponent.Ctx(ctx).Data(in.AppComponent).InsertAndGetId()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.AddComponentFailed, in.AppComponent))
	}
	out = &v1.AddOutput{Id: id}
	return out, nil
}

func (s *sComponent) Delete(ctx context.Context, in *v1.DeleteInput) (out *v1.DeleteOutput, err error) {
	// 最终删除
	rs, err := dao.AppComponent.Ctx(ctx).Where(dao.AppComponent.Columns().Id, in.Id).Delete()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteComponentFailed, in.Id))
	}
	out = &v1.DeleteOutput{}
	if out.Rows, err = rs.RowsAffected(); err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteComponentFailed, in.Id))
	}
	if out.Rows == 0 {
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteFailed, in.Id))
	}
	return out, nil
}

func (s *sComponent) Update(ctx context.Context, in *v1.UpdateInput) (out *v1.UpdateOutput, err error) {
	out = &v1.UpdateOutput{}
	out.Rows, err = dao.AppComponent.Ctx(ctx).Data(in.AppComponent).Where(dao.AppComponent.Columns().Id, in.Id).UpdateAndGetAffected()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.UpdateComponentFailed, in.AppComponent))
	}
	if out.Rows == 0 {
		return nil, gerror.NewCode(gcode.WithCode(consts.UpdateFailed, in.Id))
	}
	return out, nil
}
